// 当DOM加载完成后，为截图按钮添加点击事件监听器
document.addEventListener('DOMContentLoaded', function() {
  const startCaptureBtn = document.getElementById('startCapture');
  const captureVisibleBtn = document.getElementById('captureVisible');
  const statusDiv = document.getElementById('status');

  function showStatus(message, isError = false) {
    statusDiv.textContent = message;
    statusDiv.style.display = 'block';
    statusDiv.className = 'status ' + (isError ? 'error' : 'success');
    setTimeout(() => {
      statusDiv.style.display = 'none';
    }, 3000);
  }

  async function getCurrentTab() {
    const tabs = await chrome.tabs.query({ active: true, currentWindow: true });
    return tabs[0];
  }

  async function injectContentScript(tab) {
    try {
      await chrome.scripting.executeScript({
        target: { tabId: tab.id },
        files: ['content.js']
      });
    } catch (error) {
      console.error('注入脚本失败:', error);
      throw error;
    }
  }

  async function startCapture(action) {
    try {
      const tab = await getCurrentTab();
      
      // 检查是否可以在当前页面注入脚本
      if (!tab.url || tab.url.startsWith('chrome://')) {
        showStatus('无法在此页面使用截图功能', true);
        return;
      }

      // 注入内容脚本
      await injectContentScript(tab);

      // 发送消息到content script
      const response = await chrome.tabs.sendMessage(tab.id, { action });
      
      if (response && response.success) {
        showStatus(action === 'startCapture' ? '整页截图完成' : '当前屏幕截图完成');
      } else {
        showStatus('截图失败: ' + (response?.error || '未知错误'), true);
      }
    } catch (error) {
      console.error('截图错误:', error);
      showStatus('截图失败: ' + error.message, true);
    }
  }

  // 滚动截图按钮点击事件
  startCaptureBtn.addEventListener('click', () => {
    startCapture('startCapture');
  });

  // 当前屏幕截图按钮点击事件
  captureVisibleBtn.addEventListener('click', () => {
    startCapture('captureVisible');
  });
});
